package com.trs.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DingDingUtil {

	public static String SECRET = "";
	public static String URL = "";

	/**
	 * 组装签名url
	 * 
	 * @return url
	 */
	public static String getURL() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		Long timestamp = System.currentTimeMillis();
		String stringToSign = timestamp + "\n" + SECRET;
		Mac mac = Mac.getInstance("HmacSHA256");
		mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
		byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
		String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
		String signResult = "&timestamp=" + timestamp + "&sign=" + sign;
		// 得到拼接后的 URL
		return URL + signResult;
	}

	/**
	 * 获取客户端
	 * 
	 * @return
	 */
	public static DingTalkClient getClient() throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		return new DefaultDingTalkClient(getURL());
	}

	public static void sendText(String content, boolean isall, List<String> tolist) throws ApiException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {

		DingTalkClient client = getClient();
		OapiRobotSendRequest request = new OapiRobotSendRequest();
		request.setMsgtype("text");
		OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
		text.setContent(content);
		request.setText(text);
		OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
		// isAtAll类型如果不为Boolean，请升级至最新SDK
		at.setIsAtAll(isall);
		at.setAtMobiles(tolist);
		request.setAt(at);
		OapiRobotSendResponse response = client.execute(request);
		log.info("content:{},success:{}, code:{}, errorCode:{}, errorMsg:{}", content, response.isSuccess(), response.getCode(), response.getErrcode(), response.getErrmsg());
	}

}
